package com.wxb.auth.service;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.nacos.common.codec.Base64;
import com.wxb.auth.form.VerifyPhoneBody;
import com.wxb.auth.form.WeiXInLoginBody;
import com.wxb.common.core.utils.uuid.IdUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.wxb.common.core.constant.CacheConstants;
import com.wxb.common.core.constant.Constants;
import com.wxb.common.core.constant.SecurityConstants;
import com.wxb.common.core.constant.UserConstants;
import com.wxb.common.core.domain.R;
import com.wxb.common.core.enums.UserStatus;
import com.wxb.common.core.exception.ServiceException;
import com.wxb.common.core.text.Convert;
import com.wxb.common.core.utils.StringUtils;
import com.wxb.common.core.utils.ip.IpUtils;
import com.wxb.common.redis.service.RedisService;
import com.wxb.common.security.utils.SecurityUtils;
import com.wxb.system.api.RemoteUserService;
import com.wxb.system.api.domain.SysUser;
import com.wxb.system.api.model.LoginUser;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Objects;

/**
 * 登录校验方法
 *
 * @author wxb
 */
@Component
public class SysLoginService
{
    @Resource
    private RemoteUserService remoteUserService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysRecordLogService recordLogService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private WxMaService wxMaService;

    /**
     * 登录
     */
    public LoginUser login(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
            throw new ServiceException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new ServiceException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new ServiceException("用户名不在指定范围");
        }
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "很遗憾，访问IP已被列入系统黑名单");
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new ServiceException("登录用户：" + username + " 不存在");
        }

        if (R.FAIL == userResult.getCode())
        {
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }
        passwordService.validate(user, password);
        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
        return userInfo;
    }


    /**
     * 验证码登录
     *
     * @param phone    登录参数
     * @param smsCode 语言类型
     * @return 登录结果
     */
    public LoginUser loginPhone( String phone, String smsCode) {
        // 校验验证码是否过期
        if (StringUtils.isNull(smsCode)) {
            throw new ServiceException("对不起，您未填写短信验证码,请重新填写!");
        }
        // 从缓存中获取验证码
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + phone;
        String codeKey = redisService.getCacheObject(verifyKey);
        // 校验验证码是否过期
        if (StringUtils.isNull(codeKey)) {
            throw new ServiceException("对不起，您的短信验证码已过期!");
        }
        // 校验验证码是否正确
        if (!smsCode.equals(codeKey)) {
            throw new ServiceException("对不起，您的短信验证码错误,请重新获取!");
        }
        // 根据手机号查询是否存在这个用户
        R<LoginUser> userResult = remoteUserService.getUserInfoByPhone(phone, SecurityConstants.INNER);
        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData()))
        {
            // 不存在就创建新用户
            SysUser user = new SysUser();
            user.setUserName(IdUtils.fastSimpleUUID());
            user.setPhonenumber(phone);
            R<?> registerResult = remoteUserService.registerUserInfo(user, SecurityConstants.INNER);
            if (R.FAIL == registerResult.getCode()) {
                throw new ServiceException(registerResult.getMsg());
            }
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "手机号注册成功!");
            // 注册后再次获取用户信息
            userResult = remoteUserService.getUserInfoByPhone(phone, SecurityConstants.INNER);
        }

        if (R.FAIL == userResult.getCode())
        {
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + phone + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "该手机号的用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + phone + " 已停用");
        }
        recordLogService.recordLogininfor(phone, Constants.LOGIN_SUCCESS, "登录成功");
        // 删除验证码
        redisService.deleteObject(verifyKey);
        return userInfo;
    }

    /**
     * 一键登录
     *
     * @param param 登录参数
     * @return 登录结果
     */
    public LoginUser loginOnesTep(VerifyPhoneBody param) {
        // fixme 为实现,以后再说
        LoginUser userInfo = new LoginUser();
        return userInfo;
    }

    /**
     * 微信授权登录
     *
     * @param form    授权参数
     * @return 登录结果
     */
    public LoginUser loginWeiXin(WeiXInLoginBody form) throws WxErrorException {
        // 获取微信用户session
        WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(form.getCode());
        LoginUser userInfo =null;
        if (StringUtils.isNotEmpty(session.getOpenid())) {
            // 解析电话号码
            String phoneNumber;
            byte[] byEncrypdata = Base64.decodeBase64(form.getEncryptedData().getBytes());
            byte[] byIvdata = Base64.decodeBase64(form.getIv().getBytes());
            byte[] bySessionkey = Base64.decodeBase64(session.getSessionKey().getBytes());
            AlgorithmParameterSpec ivSpec = new IvParameterSpec(byIvdata);
            try {
                SecretKeySpec keySpec = new SecretKeySpec(bySessionkey, "AES");
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
                String phoneResult = new String(cipher.doFinal(byEncrypdata), StandardCharsets.UTF_8);
                JSONObject phoneObject = JSONObject.parseObject(phoneResult);
                phoneNumber = phoneObject.getString("phoneNumber");
            } catch (Exception e) {
                e.printStackTrace();
                throw new ServiceException("对不起，电话号码解析失败,请重试!");
            }
            // 根据openId查询是否存在这个用户
            R<LoginUser> userResult = remoteUserService.getUserInfoByOpenId(session.getOpenid(), SecurityConstants.INNER);
            if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())){
                // 创建新用户
                SysUser user = new SysUser();
                user.setUserName(form.getNickName());
                user.setNickName(form.getNickName());
                user.setPhonenumber(phoneNumber);
                user.setAvatar(form.getAvatarUrl());
                user.setOpenId(session.getOpenid());
                user.setSessionKey(session.getSessionKey());
                if (Objects.equals(form.getGender(), 0)) {
                    user.setSex("2");
                } else if (Objects.equals(form.getGender(), 1)) {
                    user.setSex("0");
                } else if (Objects.equals(form.getGender(), 2)) {
                    user.setSex("1");
                }
                R<?> registerResult = remoteUserService.registerUserInfo(user, SecurityConstants.INNER);
                if (R.FAIL == registerResult.getCode()) {
                    throw new ServiceException(registerResult.getMsg());
                }
                recordLogService.recordLogininfor(session.getOpenid(), Constants.LOGIN_FAIL, "微信注册成功!");
                userResult = remoteUserService.getUserInfoByOpenId(session.getOpenid(), SecurityConstants.INNER);
            }
            userInfo = userResult.getData();
            SysUser user = userResult.getData().getSysUser();
            if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
            {
                recordLogService.recordLogininfor(session.getOpenid(), Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
                throw new ServiceException("对不起，您的账号：" + session.getOpenid() + " 已被删除");
            }
            if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
            {
                recordLogService.recordLogininfor(session.getOpenid(), Constants.LOGIN_FAIL, "该手机号的用户已停用，请联系管理员");
                throw new ServiceException("对不起，您的账号：" + session.getOpenid() + " 已停用");
            }
            recordLogService.recordLogininfor(session.getOpenid(), Constants.LOGIN_SUCCESS, "登录成功");
        }else {
            throw new ServiceException("对不起，获取微信账号失败,请重新授权!");
        }
        return userInfo;
    }

    public void logout(String loginName)
    {
        recordLogService.recordLogininfor(loginName, Constants.LOGOUT, "退出成功");
    }

    /**
     * 注册
     */
    public void register(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password))
        {
            throw new ServiceException("用户/密码必须填写");
        }
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            throw new ServiceException("账户长度必须在2到20个字符之间");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }

        // 注册用户信息
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setNickName(username);
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        R<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);

        if (R.FAIL == registerResult.getCode())
        {
            throw new ServiceException(registerResult.getMsg());
        }
        recordLogService.recordLogininfor(username, Constants.REGISTER, "注册成功");
    }
}
